package cn.iocoder.yudao.module.system.controller.admin.gugu;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.controller.admin.gugu.convert.CeeMajorConvert;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.*;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.AllSuitableMajorsRespVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.AllSuitableMajorsPageRespVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.CeeMajorPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.CeeMajorRespVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.StructuredUserDataReqVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.StructuredUserDataPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.DirectParamsReqVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.DirectParamsGroupRespVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.SuitableMajorsReqVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.SuitableMajorsRespVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.SimulationVipStatusRespVO;
import cn.iocoder.yudao.module.system.dal.dataobject.gugu.CeeMajorDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.UserAssetsDO;
import cn.iocoder.yudao.module.system.service.gugu.CeeMajorService;
import cn.iocoder.yudao.module.system.service.gugu.MajorRecommendService;
import cn.iocoder.yudao.module.system.service.gugu.UserProfileService;
import cn.iocoder.yudao.module.system.service.user.UserAssetsService;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import cn.iocoder.yudao.module.system.util.gugu.GuGuDataUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.validation.Valid;
import java.util.Map;

import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserId;

/**
 * 大学高校专业数据查询控制器
 */
@Tag(name = "管理后台 - 大学高校专业数据查询")
@RestController
@RequestMapping("/system/metadata/ceemajor")
@Validated
@Slf4j
public class CeeMajorController {

    @Resource
    private UserProfileService userProfileService;

    @Resource
    private CeeMajorService ceeMajorService;

    @Resource
    private MajorRecommendService majorRecommendService;

    @Resource
    private UserAssetsService userAssetsService;

    @GetMapping("query")
    @Operation(summary = "查询大学高校专业数据")
    @PermitAll
    public CommonResult<CeeMajorQueryRespVO> queryCeeMajor(
            @Parameter(description = "APPKEY", required = true) @RequestParam(value = "appkey") String appkey,
            @Parameter(description = "搜索关键字，模糊匹配专业名称、学科、专业介绍、开设课程") @RequestParam(value = "keywords", required = false) String keywords,
            @Parameter(description = "每页数据量，参数最大值为20，不传默认获取所有数据") @RequestParam(value = "pagesize", required = false) Integer pagesize,
            @Parameter(description = "页码，第几页数据，第一页从1开始，不传默认获取所有数据") @RequestParam(value = "pageindex", required = false) Integer pageindex) {

        // 验证appkey是否有效
        if (!GuGuDataUtils.validateCeeMajorApiKey(appkey)) {
            return CommonResult.error(403, "无效的APPKEY");
        }

        //如果keywords中包含括号 则去掉括号及括号中的内容
        if (keywords != null && keywords.contains("(")) {
            keywords = keywords.replaceAll("\\([^\\)]*\\)", "");
        }

        // 构建请求参数
        CeeMajorQueryReqVO reqVO = new CeeMajorQueryReqVO();
        reqVO.setKeywords(keywords);

        Map<String, Object> result;

        // 判断是否需要获取所有数据
        boolean fetchAllData = (pagesize == null || pageindex == null);

        if (fetchAllData) {
            // 如果没有传递分页参数，自动获取所有数据
            result = GuGuDataUtils.getCeeMajorInfoAll(reqVO);
        } else {
            // 如果传递了分页参数，使用普通分页查询
            reqVO.setPageSize(pagesize);
            reqVO.setPageIndex(pageindex);
            result = GuGuDataUtils.getCeeMajorInfo(reqVO);
        }

        // 判断是否查询成功
        Boolean success = (Boolean) result.get("success");
        if (Boolean.TRUE.equals(success)) {
            // 构建响应VO
            CeeMajorQueryRespVO respVO = new CeeMajorQueryRespVO();
            respVO.setMajorList((List<CeeMajorInfo>) result.get("majorList"));
            respVO.setTotalCount((Integer) result.get("totalCount"));
            respVO.setPageIndex((Integer) result.get("pageIndex"));
            respVO.setPageSize((Integer) result.get("pageSize"));
            respVO.setTotalPages((Integer) result.get("totalPages"));

        // 如果是所有数据，添加标记
        if (Boolean.TRUE.equals(result.get("isAllData"))) {
            respVO.setIsAllData(true);
        }

        // 保存数据到数据库
        List<CeeMajorInfo> majorList = respVO.getMajorList();
        try {
            int savedCount = ceeMajorService.saveMajorInfoList(majorList);
            log.info("成功保存{}条专业数据到数据库", savedCount);
        } catch (Exception e) {
            log.error("保存专业数据到数据库失败", e);
            // 数据保存失败不影响API正常返回结果
        }

        return CommonResult.success(respVO);
        } else {
            String message = (String) result.get("message");
            return CommonResult.error(400, message);
        }
    }

    @PostMapping("/recommend")
    @Operation(summary = "根据用户信息推荐专业")
    @PermitAll
    public CommonResult<MajorRecommendationRespVO> recommendMajors(@RequestBody @Valid MajorRecommendationReqVO reqVO) {
        // 从用户输入中提取个人信息
        UserProfileInfo userProfile = userProfileService.extractUserProfile(reqVO.getUserInput());

        // 根据用户信息推荐专业
        Map<String, Object> recommendationResult = userProfileService.recommendMajors(userProfile);

        // 构建响应VO
        MajorRecommendationRespVO respVO = new MajorRecommendationRespVO();
        respVO.setUserProfile(userProfile);
        respVO.setHigherScoreMajors((List<MajorAdmissionInfo>) recommendationResult.get("higherScoreMajors"));
        respVO.setEqualScoreMajors((List<MajorAdmissionInfo>) recommendationResult.get("equalScoreMajors"));
        respVO.setLowerScoreMajors((List<MajorAdmissionInfo>) recommendationResult.get("lowerScoreMajors"));
        respVO.setTotalCount((Integer) recommendationResult.get("totalCount"));
        respVO.setRecommendationReason((String) recommendationResult.get("recommendationReason"));

        return CommonResult.success(respVO);
    }

    @PostMapping("/all-suitable")
    @Operation(summary = "根据结构化用户信息获取所有适合的专业（支持按需查询冲稳保等级数据）",
            description = "根据结构化用户问答数据获取适合的专业推荐。" +
                    "支持按需查询不同等级的专业数据，优化接口响应时间。\n\n" +
                    "**等级过滤说明：**\n" +
                    "- 可通过 `levelTypes` 参数指定返回的等级类型\n" +
                    "- 支持多选：rush-冲刺，stable-稳妥，safe-保底\n" +
                    "- 不传或传空数组时返回所有等级数据\n" +
                    "- 只为请求的等级查询近三年录取分数和招生计划数据，提升性能")
    @PermitAll
    public CommonResult<AllSuitableMajorsRespVO> getAllSuitableMajors(@RequestBody @Valid StructuredUserDataReqVO reqVO) {
        // 从结构化用户数据中提取个人信息
        UserProfileInfo userProfile = userProfileService.extractUserProfileFromStructuredData(reqVO.getUserAnswers());

        // 获取所有适合的专业（支持按需查询等级数据）
        Map<String, Object> result = userProfileService.getAllSuitableMajors(userProfile, reqVO.getLevelTypes());

        // 构建响应VO
        AllSuitableMajorsRespVO respVO = new AllSuitableMajorsRespVO();
        respVO.setUserProfile(userProfile);
        respVO.setRushMajors((List<MajorAdmissionInfo>) result.get("rushMajors"));
        respVO.setStableMajors((List<MajorAdmissionInfo>) result.get("stableMajors"));
        respVO.setSafeMajors((List<MajorAdmissionInfo>) result.get("safeMajors"));
        respVO.setRushCount((Integer) result.get("rushCount"));
        respVO.setStableCount((Integer) result.get("stableCount"));
        respVO.setSafeCount((Integer) result.get("safeCount"));
        respVO.setTotalCount((Integer) result.get("totalCount"));
        respVO.setQueryInfo((String) result.get("queryInfo"));
        respVO.setRequestedLevels((List<String>) result.get("requestedLevels"));

        return CommonResult.success(respVO);
    }

    @PostMapping("/all-suitable-by-params")
    @Operation(summary = "根据直接参数获取所有适合的专业（冲稳保分类，支持分组）",
            description = "根据省份、选科、高考分数等参数获取适合的专业推荐。" +
                    "支持按学校或专业分组展示，提供更好的数据组织方式。\n\n" +
                    "**分组功能说明：**\n" +
                    "- `groupType: \"school\"` - 按学校分组：将专业按学校进行分组，每个学校显示其所有专业的冲稳保分类\n" +
                    "- `groupType: \"major\"` - 按专业分组：将学校按专业进行分组，每个专业显示所有开设该专业的学校的冲稳保分类\n" +
                    "- `groupType: \"none\"` 或不传 - 不分组：保持原有的返回格式\n\n" +
                    "**分页说明：**\n" +
                    "- 分组查询支持分页功能，可指定 `pageNo` 和 `pageSize`\n" +
                    "- 不分组查询返回所有数据，不支持分页\n\n" +
                    "**返回格式：**\n" +
                    "- 分组查询：返回 `DirectParamsGroupRespVO` 格式\n" +
                    "- 不分组查询：返回 `AllSuitableMajorsRespVO` 格式\n\n" +
                    "**VIP权限说明：**\n" +
                    "- 第二页及以后的数据需要模拟志愿VIP权限\n" +
                    "- 使用高级筛选条件（感兴趣专业类别、分数范围、用户类型）需要模拟志愿VIP权限")
    @PermitAll
    public CommonResult<?>  getAllSuitableMajorsByParams(@RequestBody @Valid DirectParamsReqVO reqVO) {
        // 获取当前登录用户ID
        Long userId = getLoginUserId();

        // 检查是否需要VIP权限验证
        boolean needsVipValidation = false;

        // 1. 检查是否为第二页及以后的数据请求
        if (reqVO.getPageNo() != null && reqVO.getPageNo() > 1) {
            needsVipValidation = true;
            log.info("用户请求第{}页数据，需要VIP权限验证", reqVO.getPageNo());
        }

        // 2. 检查是否使用了高级筛选条件
        if (reqVO.getInterestedMajorCategories() != null && !reqVO.getInterestedMajorCategories().isEmpty()) {
            needsVipValidation = true;
            log.info("用户使用了感兴趣专业类别筛选，需要VIP权限验证");
        }

        if (reqVO.getMinScore() != null || reqVO.getMaxScore() != null) {
            needsVipValidation = true;
            log.info("用户使用了分数范围筛选，需要VIP权限验证");
        }

        if (reqVO.getTypeName() != null && !reqVO.getTypeName().trim().isEmpty()) {
            needsVipValidation = true;
            log.info("用户使用了用户类型筛选，需要VIP权限验证");
        }

        // 3. 如果需要VIP权限验证，则进行验证
        if (needsVipValidation) {
            log.info("开始验证用户{}的模拟志愿VIP权限", userId);
            userAssetsService.validateSimulationVipMembership(userId);
            log.info("用户{}的模拟志愿VIP权限验证通过", userId);
        }

//        if(userAssetsService.validateSimulationVipMembership(userId)){
//            reqVO.setPageNo(1);
//        }
        // 构建用户个人信息
        UserProfileInfo userProfile = new UserProfileInfo();
        userProfile.setProvince(reqVO.getProvince());
        userProfile.setSubjects(reqVO.getSubjects());
        userProfile.setTotalScore(reqVO.getTotalScore());
        userProfile.setYear(reqVO.getYear() != null ? reqVO.getYear() : 2024); // 默认2024年
        userProfile.setGender(reqVO.getGender());
        userProfile.setMinScore(reqVO.getMinScore());
        userProfile.setMaxScore(reqVO.getMaxScore());
        userProfile.setInterestedMajorCategories(reqVO.getInterestedMajorCategories());
        userProfile.setPreferredLocation(reqVO.getPreferredLocation());
        userProfile.setTypeName(reqVO.getTypeName());
        userProfile.setBatchName(reqVO.getBatchName());
        userProfile.setSchoolName(reqVO.getSchoolName());
        userProfile.setSchoolFeatures(reqVO.getSchoolFeatures());
        userProfile.setSchoolProperties(reqVO.getSchoolProperties());
        userProfile.setSchoolTypes(reqVO.getSchoolTypes());

        // 检查是否需要分组
        String groupType = reqVO.getGroupType();
        if (groupType != null && !"none".equals(groupType)) {
            // 分组查询（使用优化版本V2）
            DirectParamsGroupRespVO groupResult = userProfileService.getAllSuitableMajorsByDirectParamsWithGroupOptimizedV2(
                    userProfile, groupType, reqVO.getPageNo(), reqVO.getPageSize(), reqVO.getLevelTypes(),
                    reqVO.getIncludeMajorDetails(), reqVO.getTargetSchoolUuid());
            return CommonResult.success(groupResult);
        } else {
            // 普通查询（不分组）
            Map<String, Object> result = userProfileService.getAllSuitableMajorsByDirectParams(userProfile, reqVO.getLevelTypes());

            // 构建响应VO
            AllSuitableMajorsRespVO respVO = new AllSuitableMajorsRespVO();
            respVO.setUserProfile(userProfile);
            respVO.setRushMajors((List<MajorAdmissionInfo>) result.get("rushMajors"));
            respVO.setStableMajors((List<MajorAdmissionInfo>) result.get("stableMajors"));
            respVO.setSafeMajors((List<MajorAdmissionInfo>) result.get("safeMajors"));
            respVO.setRushCount((Integer) result.get("rushCount"));
            respVO.setStableCount((Integer) result.get("stableCount"));
            respVO.setSafeCount((Integer) result.get("safeCount"));
            respVO.setTotalCount((Integer) result.get("totalCount"));
            respVO.setQueryInfo((String) result.get("queryInfo"));

            return CommonResult.success(respVO);
        }
    }

    @PostMapping("/suitable-majors")
    @Operation(summary = "获取可填专业数据（前端专用接口）",
            description = "专门为前端设计的简化接口，返回按学校分组的可填专业数据。" +
                    "基于现有的 getSchoolGroupedMajorsOptimized 方法，但提供更适合前端的数据格式。\n\n" +
                    "**功能特点：**\n" +
                    "- 返回按学校分组的可填专业\n" +
                    "- 包含冲稳保三个等级的统计\n" +
                    "- 提供简洁的专业信息\n" +
                    "- 支持分页\n" +
                    "- 可选择返回详细专业数据\n\n" +
                    "**分页说明：**\n" +
                    "- 支持分页功能，可指定 `pageNo` 和 `pageSize`\n" +
                    "- 默认每页10条数据\n\n" +
                    "**等级过滤：**\n" +
                    "- 可通过 `levelTypes` 参数指定返回的等级类型\n" +
                    "- 支持多选：rush-冲刺，stable-稳妥，safe-保底\n" +
                    "- 不传或传空数组时返回所有等级数据")
    @PermitAll
    public CommonResult<SuitableMajorsRespVO> getSuitableMajors(@RequestBody @Valid SuitableMajorsReqVO reqVO) {
        // 构建用户个人信息
        UserProfileInfo userProfile = new UserProfileInfo();
        userProfile.setProvince(reqVO.getProvince());
        userProfile.setSubjects(reqVO.getSubjects());
        userProfile.setTotalScore(reqVO.getTotalScore());
        userProfile.setYear(reqVO.getYear() != null ? reqVO.getYear() : 2024);

        // 调用服务获取可填专业数据
        SuitableMajorsRespVO result = userProfileService.getSuitableMajorsForFrontend(
                userProfile,
                reqVO.getPageNo(),
                reqVO.getPageSize(),
                reqVO.getLevelTypes(),
                reqVO.getIncludeMajorDetails(),
                reqVO.getTargetSchoolUuid()
        );

        return CommonResult.success(result);
    }

    @PostMapping("/all-suitable/page")
    @Operation(summary = "分页获取所有适合的专业（支持按冲稳保类型分页）")
    @PermitAll
    public CommonResult<PageResult<AllSuitableMajorsPageRespVO>> getAllSuitableMajorsWithPagination(@RequestBody @Valid StructuredUserDataPageReqVO reqVO) {
        // 从结构化用户数据中提取个人信息
        UserProfileInfo userProfile = userProfileService.extractUserProfileFromStructuredData(reqVO.getUserAnswers());

        // 获取分页的专业数据
        Map<String, Object> result = userProfileService.getAllSuitableMajorsWithPagination(
                userProfile, reqVO.getPageNo(), reqVO.getPageSize(), reqVO.getMajorType());

        // 构建响应VO
        AllSuitableMajorsPageRespVO respVO = new AllSuitableMajorsPageRespVO();
        respVO.setUserProfile(userProfile);
        respVO.setMajors((List<MajorAdmissionInfo>) result.get("majors"));
        respVO.setRushCount((Integer) result.get("rushCount"));
        respVO.setStableCount((Integer) result.get("stableCount"));
        respVO.setSafeCount((Integer) result.get("safeCount"));
        respVO.setTotalCount((Integer) result.get("totalCount"));
        respVO.setCurrentMajorType((String) result.get("currentMajorType"));
        respVO.setQueryInfo((String) result.get("queryInfo"));

        // 构建分页结果
        Integer currentTypeTotal = (Integer) result.get("currentTypeTotal");
        PageResult<AllSuitableMajorsPageRespVO> pageResult = new PageResult<>();
        pageResult.setList(Arrays.asList(respVO)); // 将响应VO包装在列表中
        pageResult.setTotal(currentTypeTotal.longValue());

        return CommonResult.success(pageResult);
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询专业数据")
    @PermitAll
    public CommonResult<PageResult<CeeMajorRespVO>> getMajorPage(CeeMajorPageReqVO reqVO) {
        // 从数据库中查询专业数据

        String exactMajorName = reqVO.getExactMajorName();

        if (exactMajorName != null) {
            // 如果exactMajorName中包含括号，则去掉括号及括号中的内容
            if (exactMajorName.contains("(")) {
               exactMajorName = exactMajorName.replaceAll("\\([^\\)]*\\)", "").trim();
            }

            // 如果exactMajorName是描述性文本，尝试提取"的"后面的专业名称
            // 例如："详细介绍北京大学的软件工程" -> "软件工程"
            if (exactMajorName.contains("的")) {
                String[] parts = exactMajorName.split("的");
                if (parts.length > 1) {
                    // 取"的"后面的文本作为专业名称
                    exactMajorName = parts[parts.length - 1].trim();
                }
            }

            // 更新处理后的专业名称
            reqVO.setExactMajorName(exactMajorName);
        }

        PageResult<CeeMajorDO> pageResult = ceeMajorService.getMajorPage(reqVO);
        // 转换为 VO 对象
        return CommonResult.success(CeeMajorConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/get")
    @Operation(summary = "获取专业详情")
    @PermitAll
    public CommonResult<CeeMajorRespVO> getMajor(@RequestParam("id") Long id) {
        // 从数据库中查询专业详情
        CeeMajorDO major = ceeMajorService.getMajor(id);
        // 转换为 VO 对象
        return CommonResult.success(CeeMajorConvert.INSTANCE.convert(major));
    }

    @GetMapping("/tree")
    @Operation(summary = "获取专业树形结构")
    @PermitAll
    public CommonResult<Map<String, Object>> getMajorTree(
            @Parameter(description = "教育级别", example = "本科") @RequestParam(value = "educationLevel", required = false) String educationLevel,
            @Parameter(description = "学科门类 ID，当传递时只加载该门类下的数据") @RequestParam(value = "categoryId", required = false) String categoryId,
            @Parameter(description = "专业名称，模糊搜索", example = "计算机") @RequestParam(value = "majorName", required = false) String majorName) {
        // 获取专业树形结构，采用懒加载方式，支持专业名称搜索
        Map<String, Object> result = ceeMajorService.getMajorTree(educationLevel, categoryId, majorName);
        return CommonResult.success(result);
    }

    @GetMapping("/recommended-tree")
    @Operation(summary = "获取用户推荐专业的树形结构")
    @PermitAll
    public CommonResult<Map<String, Object>> getRecommendedMajorTree(
            @Parameter(description = "教育级别", example = "本科") @RequestParam(value = "educationLevel", required = false) String educationLevel,
            @Parameter(description = "学科门类 ID，当传递时只加载该门类下的数据") @RequestParam(value = "categoryId", required = false) String categoryId) {
        // 获取用户推荐专业的树形结构

        Long userId = getLoginUserId();

        Map<String, Object> result = ceeMajorService.getMajorTree(userId, educationLevel, categoryId);
        return CommonResult.success(result);
    }

    @GetMapping("/categories")
    @Operation(summary = "获取学科门类列表")
    @PermitAll
    public CommonResult<List<String>> getDisciplinaryCategories(
            @Parameter(description = "教育级别", example = "本科") @RequestParam(value = "educationLevel", required = false) String educationLevel) {
        // 获取学科门类列表
        List<String> categories = ceeMajorService.getDisciplinaryCategories(educationLevel);
        return CommonResult.success(categories);
    }

    @GetMapping("/subcategories")
    @Operation(summary = "获取学科子类列表")
    @PermitAll
    public CommonResult<List<String>> getDisciplinarySubCategories(
            @Parameter(description = "学科门类", required = true) @RequestParam("disciplinaryCategory") String disciplinaryCategory,
            @Parameter(description = "教育级别", example = "本科") @RequestParam(value = "educationLevel", required = false) String educationLevel) {
        // 获取学科子类列表
        List<String> subCategories = ceeMajorService.getDisciplinarySubCategories(disciplinaryCategory, educationLevel);
        return CommonResult.success(subCategories);
    }

    @GetMapping("/majors-by-subcategory")
    @Operation(summary = "获取指定学科子类下的专业列表")
    @PermitAll
    public CommonResult<List<CeeMajorRespVO>> getMajorsBySubCategory(
            @Parameter(description = "学科门类", required = true) @RequestParam("disciplinaryCategory") String disciplinaryCategory,
            @Parameter(description = "学科子类", required = true) @RequestParam("disciplinarySubCategory") String disciplinarySubCategory,
            @Parameter(description = "教育级别", example = "本科") @RequestParam(value = "educationLevel", required = false) String educationLevel) {
        // 获取专业列表
        List<CeeMajorDO> majors = ceeMajorService.getMajorsBySubCategory(disciplinaryCategory, disciplinarySubCategory, educationLevel,"");
        // 转换为 VO 对象
        return CommonResult.success(CeeMajorConvert.INSTANCE.convertList(majors));
    }

    @PostMapping("/process-recommend-data")
    @Operation(summary = "处理专业推荐数据")
    @PermitAll
    public CommonResult<String> processMajorRecommendData() {
        try {
            String result = majorRecommendService.processMajorRecommendData();
            return CommonResult.success(result);
        } catch (Exception e) {
            log.error("处理专业推荐数据失败", e);
            return CommonResult.error(500, "处理失败: " + e.getMessage());
        }
    }

    @PostMapping("/reset-recommend-status")
    @Operation(summary = "重置所有专业的推荐状态")
    @PermitAll
    public CommonResult<String> resetRecommendStatus() {
        try {
            majorRecommendService.resetAllRecommendStatus();
            return CommonResult.success("重置推荐状态成功");
        } catch (Exception e) {
            log.error("重置推荐状态失败", e);
            return CommonResult.error(500, "重置失败: " + e.getMessage());
        }
    }

    @GetMapping("/recommended-majors")
    @Operation(summary = "获取推荐专业列表")
    @PermitAll
    public CommonResult<List<CeeMajorRespVO>> getRecommendedMajors(
            @Parameter(description = "教育级别", example = "本科") @RequestParam(value = "educationLevel", required = false) String educationLevel) {
        // 查询推荐专业
        List<CeeMajorDO> recommendedMajors = ceeMajorService.getRecommendedMajors(educationLevel);

        // 转换为 VO 对象
        return CommonResult.success(CeeMajorConvert.INSTANCE.convertList(recommendedMajors));
    }

    @GetMapping("/test-major-details/{id}")
    @Operation(summary = "测试专业详细信息返回")
    @PermitAll
    public CommonResult<CeeMajorRespVO> testMajorDetails(@PathVariable("id") Long id) {
        try {
            // 查询专业详情
            CeeMajorDO major = ceeMajorService.getMajor(id);

            // 转换为 VO 对象
            CeeMajorRespVO respVO = CeeMajorConvert.INSTANCE.convert(major);

            // 记录返回的字段信息
            log.info("返回专业详情 - ID: {}, 名称: {}, 毕业规模: {}, 男女比例: {}, 推荐状态: {}, 就业方向: {}, 推荐院校数量: {}, 课程数量: {}",
                    respVO.getId(), respVO.getMajorName(), respVO.getGraduateScale(),
                    respVO.getMaleFemaleRatio(), respVO.getIsRecommended(), respVO.getCareerDirection(),
                    respVO.getRecommendSchools() != null ? respVO.getRecommendSchools().size() : 0,
                    respVO.getCourses() != null ? respVO.getCourses().size() : 0);

            return CommonResult.success(respVO);
        } catch (Exception e) {
            log.error("查询专业详情失败", e);
            return CommonResult.error(500, "查询失败: " + e.getMessage());
        }
    }

    @GetMapping("/test-career-directions")
    @Operation(summary = "测试多个就业方向的专业")
    @PermitAll
    public CommonResult<List<CeeMajorRespVO>> testCareerDirections() {
        // 查询有就业方向的推荐专业
        List<CeeMajorDO> majorsWithCareer = ceeMajorService.getRecommendedMajors(null)
                .stream()
                .filter(major -> StringUtils.hasText(major.getCareerDirection()))
                .limit(10) // 限制返回10个
                .collect(Collectors.toList());

        // 转换为 VO 对象
        List<CeeMajorRespVO> respVOs = CeeMajorConvert.INSTANCE.convertList(majorsWithCareer);

        // 记录就业方向信息
        for (CeeMajorRespVO respVO : respVOs) {
            if (StringUtils.hasText(respVO.getCareerDirection())) {
                String[] directions = respVO.getCareerDirection().split(";");
                log.info("专业: {} 有 {} 个就业方向: {}",
                        respVO.getMajorName(), directions.length, Arrays.toString(directions));
            }
        }

        return CommonResult.success(respVOs);
    }

    @GetMapping("/simulation-vip-status")
    @Operation(summary = "检查用户模拟志愿VIP状态",
            description = "检查当前登录用户的模拟志愿VIP权限状态，包括是否有效、到期时间、剩余天数等信息。\n\n" +
                    "**返回信息：**\n" +
                    "- hasVip: 是否拥有VIP权限\n" +
                    "- vipStartTime: VIP开始时间\n" +
                    "- vipEndTime: VIP结束时间\n" +
                    "- statusMessage: VIP状态描述\n" +
                    "- remainingDays: 剩余天数\n" +
                    "- expiringSoon: 是否即将过期（7天内）")
    @PermitAll
    public CommonResult<SimulationVipStatusRespVO> checkSimulationVipStatus() {
        // 获取当前登录用户ID
        Long userId = getLoginUserId();

        // 构建响应VO
        SimulationVipStatusRespVO respVO = new SimulationVipStatusRespVO();

        try {
            // 获取用户资产信息
            UserAssetsDO userAssets = userAssetsService.getUserAssetsByUserId(userId);

            if (userAssets == null) {
                // 用户资产信息不存在
                respVO.setHasVip(false);
                respVO.setStatusMessage("用户未开通模拟志愿VIP服务");
                respVO.setExpiringSoon(false);
                return CommonResult.success(respVO);
            }

            // 检查是否有模拟志愿VIP有效期
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime vipEndTime = userAssets.getSimulationEndTime();
            LocalDateTime vipStartTime = userAssets.getSimulationStartTime();

            respVO.setVipStartTime(vipStartTime);
            respVO.setVipEndTime(vipEndTime);

            if (vipEndTime != null && vipEndTime.isAfter(now)) {
                // VIP有效
                respVO.setHasVip(true);

                // 计算剩余天数
                long remainingDays = ChronoUnit.DAYS.between(now, vipEndTime);
                respVO.setRemainingDays(remainingDays);

                // 检查是否即将过期（7天内）
                boolean expiringSoon = remainingDays <= 7;
                respVO.setExpiringSoon(expiringSoon);

                if (expiringSoon) {
                    respVO.setStatusMessage(String.format("VIP有效，剩余%d天（即将过期）", remainingDays));
                } else {
                    respVO.setStatusMessage(String.format("VIP有效，剩余%d天", remainingDays));
                }

                log.info("用户{}的模拟志愿VIP状态检查：有效，剩余{}天", userId, remainingDays);
            } else {
                // VIP已过期或未开通
                respVO.setHasVip(false);
                respVO.setRemainingDays(0L);
                respVO.setExpiringSoon(false);

                if (vipEndTime == null) {
                    respVO.setStatusMessage("未开通模拟志愿VIP服务");
                } else {
                    long expiredDays = ChronoUnit.DAYS.between(vipEndTime, now);
                    respVO.setStatusMessage(String.format("VIP已过期%d天", expiredDays));
                }

                log.info("用户{}的模拟志愿VIP状态检查：无效或已过期", userId);
            }

        } catch (Exception e) {
            log.error("检查用户{}的模拟志愿VIP状态时发生异常", userId, e);
            respVO.setHasVip(false);
            respVO.setStatusMessage("VIP状态检查失败");
            respVO.setExpiringSoon(false);
        }

        return CommonResult.success(respVO);
    }
}
